package club.cearnach.api.service.impl;

import club.cearnach.entity.Movie;
import club.cearnach.api.service.IDevelopService;
import club.cearnach.api.service.IMovieService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 阮胜
 * @date 2018/5/16 22:25
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class DevelopServiceImpl implements IDevelopService {
    private final IMovieService movieService;
    private static final int IMAGE_COUNT = 35;

    public DevelopServiceImpl(IMovieService movieService) {
        this.movieService = movieService;
    }

    @Override
    public Integer randomMovieName() {
        List<Movie> allMovieList = movieService.findAll(Pageable.unpaged()).getContent();
        AtomicInteger successCount = new AtomicInteger();
        AtomicInteger atomicInteger = new AtomicInteger();
        allMovieList.forEach(movie -> {
            movie.setImageFileName("mv-it".concat(String.valueOf(atomicInteger.incrementAndGet() % IMAGE_COUNT + 1)).concat(".jpg"));
            try {
                movieService.save(movie);
                successCount.incrementAndGet();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return successCount.get();
    }

}
